package com.king.modules.system.service.impl;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.king.common.enums.DealTypeEnum;
import com.king.common.enums.ReadTypeEnum;
import com.king.common.utils.SearchUtils;
import com.king.framework.base.service.impl.YyBaseServiceImpl;
import com.king.modules.system.domain.SysMessageEntity;
import com.king.modules.system.mapper.SysMessageMapper;
import com.king.modules.system.service.SysMessageService;

/**
 * 消息 业务层
 * 
 * @author liusheng
 */
@Service
public class SysMessageServiceImpl extends YyBaseServiceImpl<SysMessageMapper, SysMessageEntity, Long> implements SysMessageService {

	
	@SuppressWarnings("unused")
	@Autowired
	private SysMessageMapper messageMapper;

	@Transactional
	@Override
	public void batchRead(Long[] ids) throws Exception {
		List<SysMessageEntity> list = findByPKS(Arrays.asList(ids));
		for (SysMessageEntity entity : list) {
			setNoticeIsnew(entity);
		}
	}

	@Transactional
	@Override
	public void batchDeal(Long[] ids) throws Exception {
    	List<SysMessageEntity> list = findByPKS(Arrays.asList(ids));
		for(SysMessageEntity entity : list){
			setNoticeIsdeal(entity);
		}
	}

	@Transactional
	@Override
	public void setNoticeIsnew(SysMessageEntity entity) throws Exception {
    	if(entity.getIsnew()==ReadTypeEnum.INREAD.getKey()){
    		return;
    	}
        entity.setIsnew(ReadTypeEnum.INREAD.getKey());
        entity.setReceivetime(new Date());
        doUpdate(entity);
    }
	
	
    public void setNoticeIsdeal(SysMessageEntity entity) throws Exception {
    	if(entity.getIsdeal().equals(DealTypeEnum.INDEAL.getKey())){
    		return;
    	}
        if (ReadTypeEnum.UNREAD.getKey().equals(entity.getIsnew())) {
            entity.setIsnew(ReadTypeEnum.INREAD.getKey());
            entity.setReceivetime(new Date());
        }
        entity.setIsdeal(DealTypeEnum.INDEAL.getKey());
        entity.setDealtime(new Date());
        doUpdate(entity);
    }

	@Override
	public List<SysMessageEntity> findByBuuidAndBtypeAndFlowid(Long bid, String btype, Long flowid) {
		QueryWrapper<SysMessageEntity> queryWrapper = SearchUtils.buildQueryWrapper();
		queryWrapper.eq("bid", bid);
		queryWrapper.eq("btype", btype);
		queryWrapper.eq("flowid", flowid);
		queryWrapper.orderByDesc("cts");
		return list(queryWrapper);
	}

}